const { URL } = require('url')
const Controller = require('egg').Controller

/**
 * @Controller 用户
 */

class UserController extends Controller {
	/**
	 *  登录
	 */
	async login() {
		const { ctx,service } = this
		const body = ctx.request.body
		const UserSerive = service.userService
		ctx.validate({
			username: {type: 'string'},
			password: {type: 'string'}
		},body)
		const _user  = await service.userService.findByUsername({
      username: body.username,
    }) 
	
		if(!_user) {
			ctx.throw(422,'账号不存在')
		}
		// 判断密码
		if(_user.password !== ctx.helper.md5(body.password)) {
			ctx.throw(422,'密码错误')
		}
		// 判断用户状态
		if( !_user.status ) {
			ctx.throw(422,'用户已被禁用')
		}
		const token = UserSerive.createToken({_id: _user._id})
	
		ctx.cookies.set('token', token, {
			maxAge: 1000 * 3600 * 5 
		})

		ctx.body = {
			code: 200,
			data: {
				user: ctx.helper._.pick(_user,'_id','nickname','username','status','avatar','createdAt','updatedAt'),
				token
			},
			message: '登录成功',
		}
	}

	/**
	 * @summary 注册用户
	 * @router post /user/register
	 * @request body register
	 * @response 200 testResponse
	 */
	async register() {
		const { ctx, service } = this
		const UserService = service.userService
		const body = ctx.request.body
		// 校验数据 
		ctx.validate({
			username: {type: 'string'},
			password: {type: 'string'},
			confirmPassword: {type: 'string'}
		})
		if(body.confirmPassword !== body.password) {
			ctx.throw(422,'两次密码不一致！')
		}
		if( await UserService.findByUsername({username: body.username}) ) {
			ctx.throw(422,'用户已存在')
		}
		const user = await UserService.register(body)

		ctx.body = {
			code: 200,
			user: ctx.helper._.pick(user,'_id','username')
		}
	}

	/**
	 * @summary 用户列表
	 * @router get /user/list
	 * @response 200 testResponse
	 * @apikey
	 */
	async list() {
		const { ctx } = this
		const User = ctx.model.User
		const users = await User.find({
			_id: {
				$ne: ctx.user._id
			}
		}).select(['nickname','_id','avatar','status'])
		ctx.body = {
			code: 200,
			data: users
		}
	}

	/**
	 * 修改密码
	 */
	async updatePassword() {
		const { ctx, service } = this
		const UserService = service.userService
		const body = ctx.request.body
		// 校验数据 
		ctx.validate({
			password: {type: 'string'},
			confirmPassword: {type: 'string'}
		})

		if(body.confirmPassword !== body.password) {
			ctx.throw(422,'两次密码不一致！')
		}
		await UserService.updatePassword(body)
		return {
			code: 200,
			message: '修改成功'
		}
	}
}

module.exports = UserController;